//
//  YTStudySearchViewController.m
//  YuTang
//
//  Created by 葛悦彣 on 2024/11/14.
//

#import "YTStudySearchViewController.h"

#import "YTStashTJModel.h"
#import "YTStudyOneTableViewCell.h"
#import "YTStudyDetailsViewController.h"
#import "YTStudyTableViewCell.h"
#import "YTVideoViewController.h"
@interface YTStudySearchViewController ()<UITextFieldDelegate>



@property (nonatomic ,strong) NSMutableArray <YTStashTJModel *> * modelArray;


@property (nonatomic ,strong) UITextField * sstextfield;

@property (nonatomic ,strong) UIButton * textRemovebtn;

@property (nonatomic ,strong) UIView * makeView;

@property (nonatomic ,strong) UIScrollView * makescrollView;

@property (nonatomic ,strong) NSString * titleStr;

@property (nonatomic ,strong) NSURLSessionDataTask * task;

@property (nonatomic ,strong) UIView * titleview;

@end

@implementation YTStudySearchViewController

-(NSMutableArray<YTStashTJModel *> *)modelArray{
    if(!_modelArray){
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

- (UIView *)makeView {
    if(!_makeView){
        _makeView = [UIView new];
        _makeView.backgroundColor = UIColor.whiteColor;
        _makeView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - Knav_HeightX);
        
        UILabel * ssls = [DTKTool labelWithText:@"历史搜索" andFont:kCFont(18) andTextColor:KcolorHex(@"#131416")];
        [_makeView addSubview:ssls];
        [ssls mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(kwt(15));
            make.top.offset(kwt(27));
        }];
        
        UIButton * scBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [scBtn setImage:[UIImage imageNamed:@"GBJL_delete"] forState:UIControlStateNormal];
        [scBtn addTarget:self action:@selector(deleteBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_makeView addSubview:scBtn];
        [scBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset(kwt(-15));
            make.top.offset(kwt(27));
            make.width.height.offset(kwt(18));
        }];
        
        self.makescrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(kwt(15), kwt(65), kwt(345), kwt(400))];
        [_makeView addSubview:self.makescrollView ];
        
        
    }
    return _makeView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIView * topview = [UIView new];
    topview.backgroundColor = KcolorHex(@"#0967FF");
    [self.view addSubview:topview];
    [topview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.height.offset(Knav_HeightX);
    }];
    MJWeakSelf
    UIView * backview = [UIView new].addClickBlock(^{
        [weakSelf popViewController];
    });
    [topview addSubview:backview];
    [backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(44);
        make.left.bottom.offset(0);
        make.width.offset(kwt(170));
    }];
    
    UIImageView * leftimg = kimageView(@"white_path");
    [backview addSubview:leftimg];
    [leftimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(20);
        make.left.offset(kwt(10));
        make.centerY.offset(0);
    }];
    
    
    UIView * ssbjview = [UIView new];
    ssbjview.backgroundColor = UIColor.whiteColor;
    [DTKTool YJ:kwt(5) andView:ssbjview];
    [topview addSubview:ssbjview];
    [ssbjview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(50));
        make.right.offset(kwt(-60));
        make.centerY.offset(KTop/2);
        make.height.offset(37);
    }];
    
    UIImageView * ssimg = kimageView(@"program_search");
    [ssbjview addSubview:ssimg];
    [ssimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(15));
        make.centerY.offset(0);
        make.height.width.offset(kwt(16));
    }];
    
    UITextField * sstextfield = [UITextField new];
    [sstextfield addTarget:self action:@selector(textFieldDidChangeValue:)  forControlEvents:UIControlEventEditingChanged];
    sstextfield.placeholder = @"搜索关键字";
    sstextfield.delegate = self;
    sstextfield.returnKeyType = UIReturnKeySearch;
    
    sstextfield.font = kFont(16);
    self.sstextfield = sstextfield;
    [ssbjview addSubview:sstextfield];
    [sstextfield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(35));
        make.right.offset(kwt(-45));
        make.top.bottom.offset(0);
    }];
    
    UIButton * textRemovebtn = [UIButton buttonWithType:0];
    self.textRemovebtn = textRemovebtn;
    textRemovebtn.hidden = YES;
    textRemovebtn.addTarget(self,@selector(textRemovebtnClick));
    [textRemovebtn setBackgroundImage:[UIImage imageNamed:@"search_delete"] forState:UIControlStateNormal];
    [ssbjview addSubview:textRemovebtn];
    [textRemovebtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(kwt(23));
        make.right.offset(kwt(-10));
        make.centerY.offset(0);
    }];
    
    UIButton * ssbtn = [UIButton buttonWithType:0];
    ssbtn.addTarget(self,@selector(back));
    [ssbtn setTitle:@"取消" forState:UIControlStateNormal];
    [ssbtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    ssbtn.titleLabel.font = kCFont(16);
    [topview addSubview:ssbtn];
    [ssbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(kwt(60));
        make.centerY.equalTo(ssbjview);
        make.right.offset(0);
    }];
    
    [self.view addSubview:self.tableview];
    self.tableview.backgroundColor = KcolorHex(@"#EBEDF0");
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.top.equalTo(topview.mas_bottom);
    }];
    [self addFooterView:^{
        [weakSelf addMoreData];
    }];
    [self addHeaderView:^{
        [weakSelf refreshingData];
    }];
    [self.view addSubview:self.makeView];
    
    [self addKeyboardNotifaction];
    [self refreshingData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 2秒后执行的代码
        [self.sstextfield becomeFirstResponder];
    });
}

///重新绘制蒙版
- (void)NewMakeViewUI{
    ///先清空
    [self.makescrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    ///获取所有数据
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray * array = [defaults objectForKey:@"YTStudySearchViewController"];
    [defaults synchronize];
    
    CGFloat X = 0;
    CGFloat Y = 0;
    CGFloat MaxW = kwt(345);
    for (NSString * str in array) {
        ///先计算文字长度
        NSString * newStr = [NSString stringWithFormat:@"  %@  ",str];
        CGFloat strW = [newStr sizeWithAttributes:@{NSFontAttributeName:kFont(16)}].width;
        UILabel * lab = [DTKTool labelWithText:newStr andFont:kFont(16) andTextColor:KcolorHex(@"#5D5D5D")];
        lab.userInteractionEnabled = YES;
        UIGTapGestureRecognizer * tap = [[UIGTapGestureRecognizer alloc]initWithTarget:self action:@selector(labClick:)];
        tap.userInfo = @{@"str":str};
        [lab addGestureRecognizer:tap];
        lab.backgroundColor = KcolorHex(@"#F8F8F8");
        [DTKTool YJ:kwt(17) andView:lab];
        if(X + strW > MaxW){
            if(X == 0){///超出最多值切是开头位置
                lab.frame = CGRectMake(X, Y, MaxW, kwt(34));
                X = 0;
                Y += kwt(43);
            } else {
                X = 0;
                Y += kwt(43);
                lab.frame = CGRectMake(X, Y, strW, kwt(34));
                X += strW + kwt(10);
            }
        } else {
            lab.frame = CGRectMake(X, Y, strW, kwt(34));
            X += strW + kwt(10);
        }
        [self.makescrollView addSubview:lab];
    }
    //    self.makescrollView.contentSize = CGSizeMake(MaxW, Y + kwt(34));
    
}

/// 删除数据
- (void)deleteBtnClick{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"" message:@"确定删除全部历史记录" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    //添加确定
    UIAlertAction *sureBtn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull   action) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:@[] forKey:@"YTStudySearchViewController"];
        [defaults synchronize];
        [self NewMakeViewUI];
        [self.view endEditing:YES];
    }];
    [sureBtn setValue:[UIColor redColor] forKey:@"titleTextColor"];
    [alertVc addAction:cancelBtn];
    [alertVc addAction :sureBtn];
    [self presentViewController:alertVc animated:YES completion:nil];
    
}
///点击
- (void)labClick:(UIGTapGestureRecognizer *)tap{
    self.sstextfield.text = [tap.userInfo objectForKey:@"str"];
    self.titleStr =  self.sstextfield.text;
    [self addtitleview];
    ///进行一次搜索动作
    [self refreshingData];
    [self keyboardWillHide];
    [self.view endEditing:YES];
}
#pragma mark - 键盘监听
- (void)addKeyboardNotifaction{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];//键盘将要显示
}
#pragma mark - 键盘将要出现
- (void)keyboardWillShow:(NSNotification *)notification{
    [self NewMakeViewUI];
    [UIView animateWithDuration:0.25 animations:^{
        self.makeView.frame = CGRectMake(0, Knav_HeightX, SCREEN_WIDTH, SCREEN_HEIGHT - Knav_HeightX);
    }];
}
- (void)keyboardWillHide{
    [UIView animateWithDuration:0.25 animations:^{
        self.makeView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - Knav_HeightX);
    }];
}


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if ([string isEqualToString:@"\n"] && textField.text.length > 0){
        //        [SVProgressHUD showInfoWithStatus:@"搜索"];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSArray * array = [defaults objectForKey:@"YTStudySearchViewController"];
        
        if(![array containsObject:textField.text]){
            NSMutableArray * newarray = [NSMutableArray arrayWithArray:array];
            [newarray addObject:textField.text];
            [defaults setObject:[NSArray arrayWithArray:newarray] forKey:@"YTStudySearchViewController"];
        }
        self.titleStr = textField.text;
        [self refreshingData];
//        添加按钮+清空文本和删除按钮
        [self addtitleview];
        [defaults synchronize];
        [self keyboardWillHide];
        [self.view endEditing:YES];
        return NO;
    }
    return YES;
}
//-(void)textFieldTextDidChangeOneCI:(NSNotification *)notification
//{
//    UITextField *textfield=[notification object];
//    if([textfield markedTextRange] == nil){
//        NSLog(@"ssssss %@",textfield.text);
//        self.titleStr = textfield.text;
//        [self refreshingData];
//        ///这里搜索
//        if (textfield.text.length > 0){
//            [self keyboardWillHide];
//        } else {
//            [self NewMakeViewUI];
//            [UIView animateWithDuration:0.25 animations:^{
//                self.makeView.frame = CGRectMake(0, Knav_HeightX, SCREEN_WIDTH, SCREEN_HEIGHT - Knav_HeightX);
//            }];
//        }
//    }
//    self.textRemovebtn.hidden = (self.sstextfield.text.length == 0);
//    
//}

- (void)textRemovebtnClick{
    self.sstextfield.text = @"";
    self.titleStr = @"";
    self.textRemovebtn.hidden = YES;
    [self.modelArray removeAllObjects];
    [self.tableview reloadData];
}
- (void)textFieldDidChangeValue:(UITextField *)sender{
//    if(sender.markedTextRange == nil){
//        NSLog(@"%@",sender.text);
//        self.titleStr = sender.text;
//        [self refreshingData];
//    }
    self.textRemovebtn.hidden = (sender.text.length == 0);
    
}
///成为第一响应
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if(self.titleview){
        [self.titleview.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self.titleview removeFromSuperview];

        self.titleview = nil;
    }
    textField.text = self.titleStr;
    self.textRemovebtn.hidden = (textField.text.length == 0);
}
- (void)addtitleview{
    self.sstextfield.text = @" ";
    self.textRemovebtn.hidden = YES;
    UIView * titleview = [UIView new];
    self.titleview = titleview;
    titleview.backgroundColor = KcolorHex(@"#EBEBEB");
    [DTKTool YJ:kwt(3) andView:titleview];
    MJWeakSelf
    titleview.addClickBlock(^{
        [weakSelf.sstextfield becomeFirstResponder];
    });
    [self.sstextfield addSubview:titleview];
    [titleview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(0);
        make.height.offset(kwt(25));
        make.right.lessThanOrEqualTo(@(kwt(-20)));
    }];
    
    UILabel * titlelab = [DTKTool labelWithText:self.titleStr andFont:kFont(16) andTextColor:KcolorHex(@"#222222")];
    [titleview addSubview:titlelab];
    [titlelab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(6));
        make.centerY.offset(0);
    }];
    
    UIImageView * Xbtn = kimageView(@"delete");
    Xbtn.addClickBlock(^{
        weakSelf.titleStr = @"";
        [weakSelf.sstextfield becomeFirstResponder];
    });
    [titleview addSubview:Xbtn];
    [Xbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titlelab.mas_right).offset(kwt(6));
        make.centerY.offset(0);
        make.right.offset(kwt(-6));
        make.width.height.offset(kwt(12));
    }];
}


- (void)refreshingData{
    self.pageNo = 1;
    [self.modelArray removeAllObjects];
    [self loadNewData];
    
}


- (void)loadNewData {
    if(self.titleStr.length < 1){
        [self.modelArray removeAllObjects];
        [self.tableview.mj_header endRefreshing];
        [self.tableview reloadData];
        return;
    }
    if(self.task){
        [self.view hideBusyHUD];
        [self.task cancel];
    }
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setObject:@(self.pageNo) forKey:@"pageNo"];
    [dict setObject:@(self.pageSize) forKey:@"pageSize"];
    [dict setObject:self.titleStr forKey:@"title"];
    [dict setObject:self.parentId forKey:@"typeId"];
    
    self.task = [SCNetManger learnInfoGetLearnInfoListWithDict:dict andCompetionHandlerBlock:^(HTTPDicBase * model) {
        [self.view hideBusyHUD];
        self.task = nil;
        if(model.code == 200){
            NSArray * array = [NSArray yy_modelArrayWithClass:YTStashTJModel.class json:model.result[@"records"]];
            if(array.count == 0 && self.modelArray.count > 0){
                [self.tableview.mj_footer endRefreshingWithNoMoreData];
            } else {
                [self.tableview.mj_footer endRefreshing];
            }
            [self.tableview.mj_header endRefreshing];
            [self.modelArray addObjectsFromArray:array];
            
            [self.tableview reloadData];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{ return YES; }
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if(self.sstextfield.text.length < 1){
        return  [UIView new];
    }
    //加入你自定义的view
    UIView * noView = [UIView new];
    UIView * NewnoView = [UIView new];
//    NewnoView.backgroundColor = UIColor.whiteColor;
    [noView addSubview:NewnoView];
    [NewnoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset(KSCREEN_WIDTH);
        make.center.offset(0);
        make.height.mas_offset(KSCREEN_HEIGHT);
    }];
    UIImageView * noImage = [UIImageView new];
    [noView addSubview:noImage];
    noImage.image = [UIImage imageNamed:@"no_search"];
    [noImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.centerY.mas_offset(-100);
    }];
    
    UILabel * noTitleLab = [UILabel new];
    [noView addSubview:noTitleLab];
    noTitleLab.text = @"暂无搜索记录\n换个关键词试试~";
    noTitleLab.textAlignment = NSTextAlignmentCenter;
    noTitleLab.numberOfLines = 2;
    noTitleLab.font = kFont(16);
    noTitleLab.textColor = [UIColor colorWithHexString:@"#262626"];
    [noTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(noImage.mas_bottom).offset(30);
        make.centerX.mas_offset(0);
    }];
    
    return noView;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  self.modelArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(self.parentId){
        return kwt(113);

    } else {
        return self.modelArray[indexPath.row].CellH;
    }
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    if(self.parentId){
        
        YTStudyOneTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"YTStudyOneTableViewCell"];
        if (cell == nil) {
            cell = [[YTStudyOneTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"YTStudyOneTableViewCell"];
        }
        if(self.modelArray.count > indexPath.row){
            cell.model = self.modelArray[indexPath.row];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        MJWeakSelf
        cell.ReloadDataBlock = ^{
            [weakSelf.tableview reloadData];
        };
        return cell ;
    } else {
        YTStudyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"YTStudyTableViewCell"];
        if (cell == nil) {
            cell = [[YTStudyTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"YTStudyTableViewCell"];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.modelArray[indexPath.row];
        MJWeakSelf
        cell.ReloadDataBlock = ^{
            [weakSelf.tableview reloadData];
        };
        cell.openvVideoBlock = ^(NSString * _Nonnull url) {
            YTVideoViewController * vc = [YTVideoViewController new];
            vc.url = url;
            vc.titleStr = weakSelf.modelArray[indexPath.row].title;
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        };
        return cell;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if([self.modelArray[indexPath.row].displayForm isEqualToString:@"1"]){
        [DTKTool openImagAndVideo:@[self.modelArray[indexPath.row].learnFileUrl] andopenview:self.view andIndex:0];
    } else{
        YTStudyDetailsViewController * vc = [YTStudyDetailsViewController new];
        vc.ID = self.modelArray[indexPath.row].ID;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}


@end
